var JcropOption = {
    actual:false,
    activate:true,
    ratio:800/557,
    croper:'producto.croper.php'
}

var imagesInOrder = false;

$(document).ready(function () {
    $('#popOferta').popover({placement:'left'});
    $('#oferta').click(check);
    
    $('#sortableImages').disableSelection().sortable();
    $('#selectCategoria').addClass('span12');
    $('#formProducto').submit(function () {
        if ($('#ofertaInput').val() == 0 && $('#selectCategoria').val() == 1) {
            $('#validadorModal').modal('show');
            return false;
        } else if (!imagesInOrder){
            ordenarImagenes();
            $('#loaderModal').modal('show')
            return false;
        } else {
            return true;
        }
    });
    fileuploaderInit();
    onfileuploaddone();
    dropzone();
    manual();
    colores();
    tags();
    $('.tagsinput').sortable({
        handle: 'span',
        stop:function () {
            var val = '';
            $('.tag span').each(function () {
                val += $(this).html().replace(/^\s+/g,'').replace(/\s+$/g,'')+'|';
            })
            val = val.slice(0,val.length-1)
            var input = $(this).attr('id').replace('_tagsinput', '').replace(/^\s+/g,'').replace(/\s+$/g,'')
            $('#'+input).val(val)
        }
    });
    $('.tagsinput').disableSelection();    
})

function onfileuploaddone () {
    $('.recortarImagen, .borrarImagen').unbind('click')
    $('.recortarImagen').click(recortarImagen)
    $('.borrarImagen').click(borrarImagen)
    $('.borrarError').click(borrarError)
}

function fileuploaderInit () {
    $('#formProducto').fileupload({
        url: BASE_URL+'admin/php/uploaders/producto.uploader.php',
        autoUpload:true,
        fileInput:$('#fileInputImages')
    })
    .bind('fileuploaddone', function (e, data) {
        $('#hiddenData').append('<input type="hidden" name="newImages[]" id="'+data.result.files[0].nombre+'" value="5" />')
        setTimeout(
            function () {
                onfileuploaddone();
            }, 
            300
        )
    })
    .bind('fileuploadfail', function (e, data){
        setTimeout(
            function () {
                onfileuploaddone();
            }, 
            300
        )
    })
}

function ordenarImagenes () {
    var data = '', id;
    $('#sortableImages li').each(function (i) {
        if (id = $(this).data('id')) {
            data += '&orden[]='+i;
            data += '&id[]='+id;
        } else {
            $('#hiddenData #'+$(this).data('nombre')).val($(this).data('nombre')+','+i+','+$(this).data('extension'))
        }
    })
    $.ajax({
        type:'POST',
        url:BASE_URL+'admin/php/controllers/ordenar.controller.php',
        data: 'tabla=imagen'+data,
        success:function () {
            imagesInOrder = true;
            $('#formProducto').submit();
        }
    })    
}

function recortarImagen () {
    crearJcrop($(this).parents('li').attr('id'))
    $('#coordenadas .nombre').val($(this).parents('li').find('.name').text())
}

function borrarImagen () {
    var data = {
        src:$(this).data('src'),
        carpeta:$(this).data('carpeta'),
        id:($(this).data('id'))?$(this).data('id'):0
    }
    console.log($(this).data('src').replace(/\.(jpg|png|gif)$/, ''))
    $('#'+$(this).data('src').replace(/\.(jpg|png|gif)$/, '')).remove();
    $.ajax({
        type:'POST',
        url:BASE_URL+'admin/php/controllers/borrarImagenes.controller.php',
        data: data
    })
    $(this).parents('li').remove();
}

function borrarError () {
    $(this).parents('li').remove();
}

function dropzone () {
    $(document).bind('dragover', function (e) {
        var dropZone = $('#dropzone'),
            timeout = window.dropZoneTimeout;
        if (!timeout) {
            dropZone.addClass('in');
        } else {
            clearTimeout(timeout);
        }
        if (e.target === dropZone[0]) {
            dropZone.addClass('hover');
        } else {
            dropZone.removeClass('hover');
        }
        window.dropZoneTimeout = setTimeout(function () {
            window.dropZoneTimeout = null;
            dropZone.removeClass('in hover');
        }, 100);
    });
}

function manual () {
    $('#manualEs, #manualPt, #manualEn').change(function() {
        $('#'+$(this).attr('id')+'Fachada').val($(this).val());
    });
    $('#modificarManualEs, #modificarManualPt, #modificarManualEn').click(function () {
        $('#'+$(this).attr('id').replace('modificarM', 'm')+'Input').show();
        $('#'+$(this).attr('id').replace('modificarM', 'm')+'Preview').hide();
    })
}

function check () {
    if ($('#oferta').hasClass('active')) {
        $('#ofertaInput').val(0);
    } else {
        $('#ofertaInput').val(1);
    }
}

function colores () {
    $.fn.colorPicker.defaults.colors = ['ff0000', 'ff9900', 'ffff00', '66cc00', '006600', '00ccff', '0033ff', 'ff66cc', '9933cc', '000000', 'ffffff', 'cccccc'];
    $('input[name="colores[]"]').colorPicker({
        showHexField: false,
        onColorChange : function(id, newValue) { console.log("ID: " + id + " has been changed to " + newValue); }
    });
    $('#colores .close').bind('click.myEvent', function () {
        $('#'+$(this).parent().data('reference')).remove();
        console.log($(this).parent().data('reference'))
        setTimeout( 
            function(){
                $('.colorPicker-palette').hide();
            },
            1
        );
    })
    $('#agregarColor').click(function () {
        var id = new Date().getTime();
        $('#colores .row-fluid').append('<input id="color'+id+'" type="text" name="colores[]" value="#ff0000" />');
        $('#color'+id).colorPicker({showHexField: false});
        $('#colores .close').unbind('click.myEvents');
        $('.colorPicker-picker:last').data('reference', 'color'+id)
        $('#colores .close').bind('click.myEvent', function () {
            $('#'+$(this).parent().data('reference')).remove();
            setTimeout( 
                function(){
                    $('.colorPicker-palette').hide();
                },
                1
            );
        })
    })
}

function tags () {
    var cache = {}
    $('#descripcionEs').tagsInput({
        autocomplete_url: BASE_URL+'admin/php/controllers/autocomplete.controller.php?language=es',
        autocomplete:{
            minLength: 2,
            source: function( request, response ) {
                var term = request.term;
                if ( term in cache ) {
                    response( cache[ term ] );
                    return;
                }
                $.getJSON( BASE_URL+'admin/php/controllers/autocomplete.controller.php?language=es', request, function( data, status, xhr ) {
                    cache[ term ] = data;
                    response( data );
                })
            },
            appendTo: '#myAutocompleContainer'
        },
        height:'150px',
        width:'99%',
        defaultText: '',
        delimiter:'|',
        onAddTag: function () {
            $('#descripcionEs_tag').autocomplete( "close" )
        }
    })
    $('#descripcionPt').tagsInput({
        autocomplete_url: BASE_URL+'admin/php/controllers/autocomplete.controller.php?language=pt',
        autocomplete:{
            minLength: 2,
            source: function( request, response ) {
                var term = request.term;
                if ( term in cache ) {
                    response( cache[ term ] );
                    return;
                }
                $.getJSON( BASE_URL+'admin/php/controllers/autocomplete.controller.php?language=pt', request, function( data, status, xhr ) {
                    cache[ term ] = data;
                    response( data );
                })
            },
            appendTo: '#myAutocompleContainer'
        },
        height:'150px',
        width:'99%',
        defaultText: '',
        delimiter:'|',
        onAddTag: function () {
            $('#descripcionPt_tag').autocomplete( "close" )
        }
    })
    $('#descripcionEn').tagsInput({
        autocomplete_url: BASE_URL+'admin/php/controllers/autocomplete.controller.php?language=en',
        autocomplete:{
            minLength: 2,
            source: function( request, response ) {
                var term = request.term;
                if ( term in cache ) {
                    response( cache[ term ] );
                    return;
                }
                $.getJSON( BASE_URL+'admin/php/controllers/autocomplete.controller.php?language=en', request, function( data, status, xhr ) {
                    cache[ term ] = data;
                    response( data );
                })
            },
            appendTo: '#myAutocompleContainer'
        },
        height:'150px',
        width:'99%',
        defaultText: '',
        delimiter:'|',
        onAddTag: function () {
            $('#descripcionEn_tag').autocomplete( "close" )
        }
    })
}